﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace TombMedia.Extensions.Date
{
    public static class DateUtility
    {
        public static byte WeekOfYear(this DateTime d)
        {
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-CA");
            var week = ci.Calendar.GetWeekOfYear(d,
                System.Globalization.CalendarWeekRule.FirstFourDayWeek,
                DayOfWeek.Monday);
            return Convert.ToByte(week);
        }
        public static double ToMilliseconds(this long ticks)
        {
            return TimeSpan.FromTicks(ticks).TotalMilliseconds;
        }
        public static DateTime ToStartofWeek(this DateTime d)
        {
            return d.Date.AddDays(d.DayOfWeek == DayOfWeek.Sunday ? -6 : -(int)d.DayOfWeek + 1);
        }
        public static DateTime FirstDateOfWeek(this int year, int weekNum)
        {
            return FirstDateOfWeek(Convert.ToInt16(year), Convert.ToByte(weekNum));
        }
        public static DateTime FirstDateOfWeek(this short year, byte weekNum)
        {
            if (new DateTime(year, 1, 1).DayOfWeek == DayOfWeek.Sunday)
            {
                weekNum = Convert.ToByte(weekNum - 1);
            }

            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-CA");

            DateTime jan1 = new DateTime(year, 1, 1);

            int daysOffset = (int)DayOfWeek.Monday - (int)jan1.DayOfWeek;

            DateTime firstMonday = jan1.AddDays(daysOffset);

            int firstWeek = ci.Calendar.GetWeekOfYear(jan1, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

            if (firstWeek <= 1)
            {
                weekNum -= 1;
            }

            return firstMonday.AddDays(weekNum * 7);

        }
    }
}
